package controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class ProcesarImagenServlet extends MyCoolServlet {

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileUploadException {

        ServletContext contexto = request.getServletContext();
            /* Nos irá generando los items y según su tamaño los guardará¡ en memoria.*/
            DiskFileItemFactory fileItem = new DiskFileItemFactory();
            /* Creamos un manejador para todos los items de la peticiÃ³n.*/
            ServletFileUpload upload = new ServletFileUpload(fileItem);
           /* Obtenemos la lista con todos los items de la peticiÃ³n.*/
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()){
                FileItem item = (FileItem) iter.next();
                    /*Si no es un tipo file.*/
                    if (item.isFormField()) {
                        request.setAttribute (item.getFieldName(),item.getString());  
                    }else{
                            /* Tipo file.*/
                            if (item.getContentType().contains("image")){ //Comprobamos que es una imagen                                
                                /*Guarmados el file.*/
                                String pathWeb  = contexto.getRealPath("../../web");
                                String path= pathWeb + "/images\\APP_" + (String)request.getAttribute("nombre") + '_' + (String)request.getAttribute("so") +".jpg";
                                pathWeb = contexto.getRealPath("/");
                                String pathBuild= pathWeb + "/images\\APP_" + (String)request.getAttribute("nombre")+ '_' + (String)request.getAttribute("so")+".jpg";
                                try {

                                    File saveToBuild = new File(pathBuild);
                                    item.write(saveToBuild);
                                    File saveTo = new File(path);

                                    FileInputStream in = new FileInputStream(saveToBuild);
                                    FileOutputStream out = new FileOutputStream(saveTo);

                                    int c;
                                    while( (c = in.read() ) != -1)
                                        out.write(c);
                                    in.close();
                                    out.close();
                                }
                                catch (Exception e){
                                    System.out.println("Ha ocurrido un error cuando intentábamos guardar el fichero cargado.");
                                }

                            }
                        }
                }
                String form = (String) request.getAttribute("form");
                if (form == null || (persistenceMechanism != null
                                    && persistenceMechanism.equals("none"))) {
                    gotoURL(errorForm, request, response);
                } else if (form.equals("createServlet")) {
                    gotoNamedResource(createServlet, request, response);
                } else {
                    gotoURL(errorForm, request, response);
                }
    }
}